package edu.tgc.web.controller.student;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;

import javax.persistence.Id;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.abyss.common.web.controller.easyui.CommonCrudEasyUiController;
import org.abyss.common.web.controller.easyui.EasyuiAjaxFormResult;
import org.abyss.common.web.controller.easyui.EasyuiResultBuilder;
import org.abyss.data.specifications.Rule;
import org.abyss.dictionary.service.DictionaryEasyUiService;
import org.apache.commons.codec.language.bm.PhoneticEngine;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFComment;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import edu.tgc.entity.hrm.IdCade;
import edu.tgc.entity.hrm.dictionary.HrmEducationType;
import edu.tgc.entity.hrm.dictionary.HrmEmployeeStatus;
import edu.tgc.entity.student.TbClass;
import edu.tgc.entity.student.TbStudent;
import edu.tgc.service.hrm.IdCadeService;
import edu.tgc.service.student.StudentService;
import edu.tgc.service.student.TbClassService;
import edu.tgc.web.form.student.StudentForm;
@Controller
@RequestMapping(value="/student/student")
public class StudentController extends CommonCrudEasyUiController<TbStudent, UUID, StudentForm> {
	
	@Autowired
	private IdCadeService idCadeService;
	@Autowired
	private TbClassService classSerivce;
	@Autowired
	private DictionaryEasyUiService dictionaryService;
	@Autowired
	private StudentService studentService;
	@Override
	public Specification<TbStudent> buildSearch(StudentForm form) {
		HashSet<Rule> rules=new HashSet<>();
		String name=form.getName();
		if(StringUtils.hasText(name)){
			rules.add(Rule.property("cade.name").contain(name));
		}
		String idNo=form.getIdNo();
		if(StringUtils.hasText(idNo)){
			rules.add(Rule.property("cade.idNo").contain(idNo));
		}
		String sex=form.getSex();
		if(StringUtils.hasText(sex)){
			rules.add(Rule.property("cade.sex").equal(sex));
		}
		String nation=form.getNation();
		if(StringUtils.hasText(nation)){
			rules.add(Rule.property("cade.nation").contain(nation));
		}
		String stuNo = form.getStuNo();
		if(StringUtils.hasText(stuNo)){
			rules.add(Rule.property("stuNo").contain(stuNo));
		}
		TbClass banji = form.getBanji();
		if(banji!=null){
			rules.add(Rule.property("banji.id").equal(banji.getId()));
		}
		String duty = form.getDuty();
		if(StringUtils.hasText(duty)){
			rules.add(Rule.property("duty").contain(duty));
		}
		String qq = form.getQq();
		if(StringUtils.hasText(qq)){
			rules.add(Rule.property("qq").contain(qq));
		}
		String address = form.getAddress();
		if(StringUtils.hasText(address)){
			rules.add(Rule.property("address").contain(address));
		}
		String phone = form.getPhone();
		if(StringUtils.hasText(phone)){
			rules.add(Rule.property("photo").contain(phone));
		}
		Integer isUsed = form.getIsUsed();

		if(isUsed==null||isUsed==1){
			rules.add(Rule.property("isUsed").equal(1));
		}else if(isUsed==0){
			rules.add(Rule.property("isUsed").equal(0));
		}
		Date createTimeB = form.getCreateTimeB();
		if(createTimeB!=null){
			rules.add(Rule.property("createTime").greaterThanOrEqualTo(createTimeB));
		}
		String searchKey = form.getSearchKey();
		if(StringUtils.hasText(searchKey)){
			rules.add(Rule.or(Rule.property("cade.name").contain(searchKey),Rule.property("cade.idNo").contain(searchKey),Rule.property("banji.name").contain(searchKey)));
		}
		return Rule.and(rules).toSpecification();
	}

	@Override
	@Transactional
	public EasyuiAjaxFormResult create(StudentForm form, BindingResult bindingResult, Model model,
			RedirectAttributes redirectAttributes) {
		IdCade cade = form.getCade();
		if(cade!=null){
			cade=idCadeService.findById(cade.getId());
			cade.setIsUsed(true);
			idCadeService.save(cade);
		}
		return super.create(form, bindingResult, model, redirectAttributes);
	}

	@Override
	@Transactional
	public EasyuiAjaxFormResult update(StudentForm form, BindingResult bindingResult, Model model,
			RedirectAttributes redirectAttributes) {
		UUID id = form.getId();
		TbStudent student = baseService.getById(id);
		IdCade cade = student.getCade();
		if(cade!=null){
			//cade=idCadeService.findById(cade.getId());
			cade.setIsUsed(false);
			idCadeService.save(cade);
		}
		cade = form.getCade();
		if(cade!=null){
			cade=idCadeService.findById(cade.getId());
			cade.setIsUsed(true);
			idCadeService.save(cade);
		}
		return super.update(form, bindingResult, model, redirectAttributes);
	}

	@Override
	@Transactional
	public EasyuiAjaxFormResult delete(StudentForm form, BindingResult bindingResult, Model model,
			RedirectAttributes redirectAttributes) {
		UUID id = form.getId();
		TbStudent student = baseService.getById(id);
		IdCade cade = student.getCade();
		if(cade!=null){
			cade.setIsUsed(false);
			idCadeService.save(cade);
		}
		return super.delete(form, bindingResult, model, redirectAttributes);
	}
	
	@RequestMapping(value="/exportSpan")
	public Object exportSpan(HttpServletRequest request , HttpServletResponse response) throws IOException{
		String[] excelHeader = { "姓名", "身份证号码","性别","学号","民族","出生日期","家庭住址","开始时间","结束时间","发证机关","班级","人员种类","手机号码","qq号码"};
		HSSFWorkbook wb = new HSSFWorkbook();  
        HSSFSheet sheet = wb.createSheet("学生信息导入表");  
        HSSFRow row = sheet.createRow((int) 0);  
        HSSFCellStyle style = wb.createCellStyle();  
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        
        for(int i=0;i<excelHeader.length;i++){
        	HSSFCell cell=row.createCell(i);
        	cell.setCellValue(excelHeader[i]);
        	cell.setCellStyle(style);  
            sheet.setColumnWidth(i, 16*256); 
        }
        HSSFPatriarch patr=sheet.createDrawingPatriarch();
        HSSFClientAnchor anchor = patr.createAnchor(0, 0, 0, 0, excelHeader.length, 1, excelHeader.length+3, 2);//创建批注位置
        HSSFComment comment = patr.createCellComment(anchor);//创建批注
        comment.setString(new HSSFRichTextString("值为\"男\"，\"女\""));//设置批注内容
        comment.setAuthor("罗建川");//设置批注作者
        comment.setVisible(false);//设置批注默认显示
        HSSFCell cell = row.getCell(2);
        cell.setCellComment(comment);//把批注赋值给单元格
        anchor=patr.createAnchor(0, 0, 0, 0, excelHeader.length, 3, excelHeader.length+3, 4);
        comment=patr.createCellComment(anchor);
        comment.setAuthor("罗建川");
        comment.setString(new HSSFRichTextString("身份证的起始有效时间"));
        cell=row.getCell(7);
        cell.setCellComment(comment);
        anchor=patr.createAnchor(0, 0, 0, 0, excelHeader.length, 5, excelHeader.length+3, 6);
        comment=patr.createCellComment(anchor);
        comment.setAuthor("罗建川");
        comment.setString(new HSSFRichTextString("身份证的结束有效时间"));
        cell=row.getCell(8);
        cell.setCellComment(comment);
        String str1=classSerivce.getClassNames();
        anchor=patr.createAnchor(0, 0, 0, 0, excelHeader.length, 7, excelHeader.length+3, 8);
        comment=patr.createCellComment(anchor);
        comment.setAuthor("罗建川");
        comment.setString(new HSSFRichTextString(str1));
        cell=row.getCell(10);
        cell.setCellComment(comment);
        Sort sort=new Sort("sort");
        @SuppressWarnings("unchecked")
		List<HrmEmployeeStatus> list = (List<HrmEmployeeStatus>) dictionaryService.getList(HrmEmployeeStatus.class,sort);
        String str="";
		for (HrmEmployeeStatus status : list) {
			str+=status.getName()+"\r\n";
		}
		if(str.length()>0){
			str=str.substring(0, str.length()-2);
		}
		str="可填值为：\r\n"+str;
        anchor=patr.createAnchor(0, 0, 0, 0, excelHeader.length, 9, excelHeader.length+3, 10);
        comment=patr.createCellComment(anchor);
        comment.setAuthor("罗建川");
        comment.setString(new HSSFRichTextString(str));
        cell=row.getCell(11);
        cell.setCellComment(comment);
        
        //设定身份证号，电话和qq为字符类型
        HSSFCellStyle style2 = wb.createCellStyle();
        HSSFDataFormat format = wb.createDataFormat(); 
        style2.setDataFormat(format.getFormat("@"));
        sheet.setDefaultColumnStyle(12, style2);
        sheet.setDefaultColumnStyle(13, style2);
        sheet.setDefaultColumnStyle(1, style2);
        response.setContentType("application/vnd.ms-excel");  
        response.setHeader("Content-disposition", "attachment;filename=student.xls");  
        OutputStream ouputStream = response.getOutputStream();  
        wb.write(ouputStream);  
        ouputStream.flush();  
        ouputStream.close();
        wb.close();
		return null;
	}

	@RequestMapping(value="/importStuManage")
	public String importStuManage(){
		return "student/student/importStuManage";
	}
	
	@RequestMapping(value="/importStu",method=RequestMethod.GET)
	public String importStu(){
		return "student/student/importStu";
	}
	
	@RequestMapping(value="/importStu",method=RequestMethod.POST)
	@ResponseBody
	public Object importStu(MultipartFile excelFile) throws IOException{
	   	HSSFWorkbook wb=new HSSFWorkbook(excelFile.getInputStream());
    	try {
    		String msg=studentService.importStu(wb);
    		//wb.close();
    		if(StringUtils.hasText(msg)){
    			return EasyuiResultBuilder.buildAjaxResult(msg);
    		}
    		return EasyuiResultBuilder.buildAjaxResult("用户数据导入成功");
		} catch (Exception e) {
			return EasyuiResultBuilder.buildAjaxResultError("用户导入失败");
		}
 	}
}
